package com.endurance.decorate.impl;

import com.alibaba.fastjson.JSON;
import com.endurance.decorate.CacheComponent;
import com.endurance.mapper.UserMapper;
import com.endurance.pojo.UserEntity;
import com.endurance.utils.JVMCacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: sunlin
 * @Date: 2024-05-16 17:57
 * @Version: 1.0
 * @Description: JVM 一级缓存
 */
@Component
@Slf4j
public class JVMCache implements CacheComponent {

    @Autowired
    private UserMapper userMapper;

    @Override
    public <T> T getCache(String key, Class<T> t, ProceedingJoinPoint joinpoint) {
        // 查询一级缓存
        T JVMCacheUser = JVMCacheUtils.getEntity(key, t);
        if (JVMCacheUser != null) {
            return (T) JVMCacheUser;
        }

        /*  UserEntity dataBaseUser = userMapper.getUser(1);
        if (dataBaseUser == null) {
            return null;
        }*/
        // 使用AOP替代此段代码
        Object dataBaseUser = null;
        try {
            // 调用目标方法，从数据库中获取
            dataBaseUser = joinpoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        if (dataBaseUser == null) {
            return null;
        }
        log.info("返回数据库中的数据：{}", JSON.toJSONString(dataBaseUser));
        // 如果数据库中有数据把数据存入到一级缓存
        JVMCacheUtils.putEntity(key, dataBaseUser);
        log.info("一级缓存中的数据：{}", JVMCacheUtils.cacheMap);
        return (T) dataBaseUser;
    }


}
